package com.wac.blog.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wac.blog.pojo.Comment;
import com.wac.blog.pojo.Question;
import com.wac.blog.pojo.QuestionCategory;
import com.wac.blog.pojo.User;
import com.wac.blog.service.CommentService;
import com.wac.blog.service.QuestionCategoryService;
import com.wac.blog.service.QuestionService;
import com.wac.blog.utils.Utils;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wac
 * @since 2020-08-04
 */
@Controller
@RequestMapping("/question")
public class QuestionController {
    @Autowired
    QuestionService questionService;

    @Autowired
    QuestionCategoryService questionCategoryService;

    @Autowired
    CommentService commentService;

    //问题展示
    @RequestMapping("/list")
    public String list(Model model){
        Page<Question> page = new Page<>(1, 10);
        questionService.page(page,new QueryWrapper<Question>().orderByDesc("gmt_create").orderByDesc("views").orderByDesc("status"));
        //获取结果
        List<Question> questionList = page.getRecords();
        model.addAttribute("questionList", questionList);
        model.addAttribute("page",page);

        List<QuestionCategory> questionCategoryList = questionCategoryService.list(null);
        model.addAttribute("questionCategoryList",questionCategoryList );
        return "question/list";
    }

    @RequestMapping("/listView")
    public String listView(Model model){
        Page<Question> page = new Page<>(1, 10);
        questionService.page(page,new QueryWrapper<Question>().orderByDesc("views").orderByDesc("gmt_create").orderByDesc("status"));
        //获取结果
        List<Question> questionList = page.getRecords();
        model.addAttribute("questionList", questionList);
        model.addAttribute("page",page);

        List<QuestionCategory> questionCategoryList = questionCategoryService.list(null);
        model.addAttribute("questionCategoryList",questionCategoryList );
        return "question/list";
    }

    @RequestMapping("/listStatus")
    public String listStatus(Model model){
        Page<Question> page = new Page<>(1, 10);
        questionService.page(page,new QueryWrapper<Question>().orderByDesc("status").orderByDesc("views").orderByDesc("gmt_create"));
        //获取结果
        List<Question> questionList = page.getRecords();
        model.addAttribute("questionList", questionList);
        model.addAttribute("page",page);

        List<QuestionCategory> questionCategoryList = questionCategoryService.list(null);
        model.addAttribute("questionCategoryList",questionCategoryList );
        return "question/list";
    }

    //根据分类问题展示
    @RequestMapping("/list/{current}/{thisCategoryName}")
    public String listByPage(Model model,@PathVariable Integer current,@PathVariable(required = false) String thisCategoryName){
        if (current<1){
            current=1;
        }
        Page<Question> page = new Page<>(current, 10);
        List<Question> questionList = new ArrayList<>();
        if (thisCategoryName==null || thisCategoryName.equals("null")){
            questionService.page(page,new QueryWrapper<Question>().orderByDesc("gmt_create"));
            questionList = page.getRecords();
        }else {
            questionService.page(page,new QueryWrapper<Question>().orderByDesc("gmt_create").eq("category_name", thisCategoryName));
            questionList = page.getRecords();
//            model.addAttribute("thisCategoryName",thisCategoryName);
        }
        model.addAttribute("questionList", questionList);
        model.addAttribute("page",page);
        List<QuestionCategory> questionCategoryList = questionCategoryService.list(null);
        model.addAttribute("questionCategoryList",questionCategoryList );
        return "question/list";
    }

    //根据id进行查看
    @RequestMapping("/read/{qid}")
    public String read(@PathVariable String qid,Model model){
        Question question = questionService.getOne(new QueryWrapper<Question>().eq("qid", qid));
        model.addAttribute("question", question);
        question.setViews(question.getViews()+1);
        questionService.updateById(question);
        List<Comment> commentList = commentService.list(new QueryWrapper<Comment>().eq("topic_id", qid));
        model.addAttribute("commentList",commentList );
        return "question/read";
    }

    @GetMapping("/write")
    public String towrite(Model model){
        List<QuestionCategory> categoryList = questionCategoryService.list(null);
        model.addAttribute("categoryList",categoryList );
        return "question/write";
    }

    @PostMapping("/write")
    public String write(Question question,HttpSession session, HttpServletRequest request){
        User loginUser = (User) session.getAttribute("loginUser");
        question.setAuthorName(loginUser.getUsername());
        question.setAuthorId(loginUser.getUid());
        question.setAuthorAvatar(loginUser.getAvatar());
        question.setQid(Utils.getUuid());
        question.setGmtCreate(Utils.getTime());
        question.setGmtUpdate(Utils.getTime());
        question.setStatus(0);
        question.setViews(0);
        question.setSort(0);
        QuestionCategory questionCategory = questionCategoryService.getById(question.getCategoryId());
        question.setCategoryName(questionCategory.getCategory());
        questionService.save(question);
        return "redirect:/question/list";
    }

    @GetMapping("/editor/{uid}/{qid}")
    public synchronized String toeditor(@PathVariable String uid,@PathVariable String qid,Model model){
        Question question = questionService.getOne(new QueryWrapper<Question>().eq("qid",qid ));
        if (!uid.equals(question.getAuthorId())){
            Utils.print("禁止以非作者身份进行编辑");
        }
        model.addAttribute("question", question);
        List<QuestionCategory> categoryList = questionCategoryService.list(null);
        model.addAttribute("categoryList", categoryList);
        return "question/editor";
    }

    @PostMapping("/editor")
    public String editor(Question question){
        Question questionSave = questionService.getOne(new QueryWrapper<Question>().eq("qid", question.getQid()));
        questionSave.setTitle(question.getTitle());
        questionSave.setContent(question.getContent());
        questionSave.setCategoryId(question.getCategoryId());
        questionSave.setGmtUpdate(Utils.getTime());
        questionService.updateById(questionSave);
        return "redirect:/question/read/"+question.getQid();
    }

    //问题删除
    @RequestMapping("/delete/{uid}/{qid}")
    public String delete(@PathVariable String uid,@PathVariable String qid){
        Question question = questionService.getOne(new QueryWrapper<Question>().eq("qid", qid));
        if (question.getAuthorId().equals(uid)){
            Utils.print("禁止以非作者身份进行删除");
        }
        questionService.removeById(question);
        return "redirect:/question/list";
    }

    //评论保存
    @RequestMapping("/comment/{qid}")
    public String commentSave(@PathVariable String qid,Comment comment){
        comment.setCommentId(Utils.getUuid());
        comment.setTopicCategory(2);
        comment.setGmtCreate(Utils.getTime());
        commentService.save(comment);
        Question question = questionService.getOne(new QueryWrapper<Question>().eq("qid", qid));
        question.setStatus(1);
        questionService.updateById(question);
        return "redirect:/question/read/"+qid;
    }

    // md 图片上传
    @ApiOperation(value = "md文件上传问题")
    @RequestMapping("/write/file/upload")
    @ResponseBody
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {

        //获得SpringBoot当前项目的路径：System.getProperty("user.dir")
//        String path = System.getProperty("user.dir")+"/upload/";
        String path = System.getProperty("user.dir")+"/src/main/resources/static/images/upload";

        //按照月份进行分类：
//        Calendar instance = Calendar.getInstance();
//        String month = (instance.get(Calendar.MONTH) + 1)+"月";
//        path = path+month;

        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }

        //上传文件地址
        Utils.print("上传文件保存地址："+realPath);

        //解决文件名字问题：我们使用uuid;
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = file.getOriginalFilename();
        // KuangUtils.print(originalFilename);
        assert originalFilename != null;
        int i = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(i + 1);

        String outFilename = filename + "."+suffix;
        Utils.print("文件名：" + outFilename);

        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath +"/"+ outFilename));

        //给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url","/upload/"+ outFilename);
        res.put("success", 1);
        res.put("message", "upload success!");
        Utils.print(res.toJSONString());

        return res;
    }
}

